﻿/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode ret=null;
for(int i=0;i<lists.length;i++){
ret=mergeTwoLists(ret,lists[i]);
}
return ret;
    }
    public ListNode mergeTwoLists(ListNode a,ListNode b){
        if(a==null||b==null){
            return  a==null?b:a;
        }
ListNode head=new ListNode(0);
ListNode aPtr=a;
ListNode bPtr=b;
ListNode H=head;
while(aPtr!=null&&bPtr!=null){
    if(aPtr.val<bPtr.val){
        H.next=aPtr;
        aPtr=aPtr.next;
    }else{
        H.next=bPtr;
        bPtr=bPtr.next;
    }
    H=H.next;
}
H.next=(aPtr==null)?bPtr:aPtr;
return head.next;
    }
}